package com.hrm.social.service;

import com.alibaba.fastjson.JSON;
import com.hrm.common.entity.Result;
import com.hrm.common.util.IdWorker;
import com.hrm.domain.employee.UserCompanyPersonal;
import com.hrm.domain.social_security.Archive;
import com.hrm.domain.social_security.ArchiveDetail;
import com.hrm.domain.social_security.CityPaymentItem;
import com.hrm.domain.social_security.UserSocialSecurity;
import com.hrm.social.client.EmployeeFeignClient;
import com.hrm.social.dao.ArchiveDao;
import com.hrm.social.dao.ArchiveDetailDao;
import com.hrm.social.dao.UserSocialSecurityDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
@Transactional
public class ArchiveService {

    @Autowired
    private ArchiveDao archiveDao;
    @Autowired
    private ArchiveDetailDao archiveDetailDao;
    @Autowired
    private UserSocialSecurityDao userSocialSecurityDao;
    @Autowired
    private EmployeeFeignClient employeeFeignClient;
    @Autowired
    private UserSocialService userSocialService;
    @Autowired
    private PaymentItemService paymentItemService;
    @Autowired
    private IdWorker idWorker;

    public Archive findArchive(String companyId, String yearMonth) {
        return archiveDao.findByCompanyIdAndYearsMonth(companyId,yearMonth);

    }

    public List<ArchiveDetail> findAllDetailByArchiveId(String id) {
        return archiveDetailDao.findByArchiveId(id);
    }

    public List<ArchiveDetail> getReport(String companyId, String yearMonth) {
        //查询用户的社保列表 (用户和基本社保数据)
        Page<Map<String,Object>> userSocialSecurityItemPage = userSocialSecurityDao.findPage(companyId,null);

        List<ArchiveDetail> list = new ArrayList<>();

        for (Map map : userSocialSecurityItemPage) {
            //构造数据
            String userId = (String)map.get("userId");
            String mobile = (String)map.get("mobile");
            String username = (String)map.get("username");
            String departmentName = (String)map.get("departmentName");
            ArchiveDetail vo = new ArchiveDetail(userId,mobile,username,departmentName);
            vo.setTimeOfEntry((Date) map.get("timeOfEntry"));
            //获取员工个人信息
            Result personalResult = employeeFeignClient.findPersonalInfo(vo.getUserId());
            if (personalResult.isSuccess()) {
                UserCompanyPersonal userCompanyPersonal = JSON.parseObject(JSON.toJSONString(personalResult.getData()), UserCompanyPersonal.class);
                vo.setUserCompanyPersonal(userCompanyPersonal);
            }
            //社保相关信息
            getOtherData(vo, yearMonth);
            list.add(vo);
        }
        return list;
    }

    /**
     * 企业员工的社保和公积金费用计算相加
     * @param vo
     * @param yearMonth
     */
    public void getOtherData(ArchiveDetail vo, String yearMonth) {

        UserSocialSecurity userSocialSecurity = userSocialService.findById(vo.getUserId());
        if(userSocialSecurity == null) {
            return;
        }

        BigDecimal socialSecurityCompanyPay = new BigDecimal(0);

        BigDecimal socialSecurityPersonalPay = new BigDecimal(0);

        List<CityPaymentItem> cityPaymentItemList = paymentItemService.findAllByCityId(userSocialSecurity.getProvidentFundCityId());

        for (CityPaymentItem cityPaymentItem : cityPaymentItemList) {
            if (cityPaymentItem.getSwitchCompany()) {
                BigDecimal augend;
                if (cityPaymentItem.getPaymentItemId().equals("4") && userSocialSecurity.getIndustrialInjuryRatio() != null) {
                    augend = userSocialSecurity.getIndustrialInjuryRatio().multiply(userSocialSecurity.getSocialSecurityBase());
                } else {
                    augend = cityPaymentItem.getScaleCompany().multiply(userSocialSecurity.getSocialSecurityBase());
                }
                BigDecimal divideAugend = augend.divide(new BigDecimal(100));
                socialSecurityCompanyPay = socialSecurityCompanyPay.add(divideAugend);
            }
            if (cityPaymentItem.getSwitchPersonal()) {
                BigDecimal augend = cityPaymentItem.getScalePersonal().multiply(userSocialSecurity.getSocialSecurityBase());
                BigDecimal divideAugend = augend.divide(new BigDecimal(100));
                socialSecurityPersonalPay = socialSecurityPersonalPay.add(divideAugend);
            }
        }

        vo.setSocialSecurity(socialSecurityCompanyPay.add(socialSecurityPersonalPay));
        vo.setSocialSecurityEnterprise(socialSecurityCompanyPay);
        vo.setSocialSecurityIndividual(socialSecurityPersonalPay);
        vo.setUserSocialSecurity(userSocialSecurity);
        vo.setSocialSecurityMonth(yearMonth);
        vo.setProvidentFundMonth(yearMonth);
    }

    /**
     * 社保数据归档,保存在数据库archive和archiveDetail表中
     * @param yearMonth
     * @param companyId
     */
    public void archive(String yearMonth, String companyId) {
        //查询归档数据
        List<ArchiveDetail> archiveDetails = getReport(companyId, yearMonth);
        //计算当月企业与员工的支出所有社保金额
        BigDecimal enterMoney = new BigDecimal(0);
        BigDecimal personMoney = new BigDecimal(0);
        for (ArchiveDetail archiveDetail : archiveDetails) {
            BigDecimal e1 = archiveDetail.getProvidentFundEnterprises() == null ? new BigDecimal(0) : archiveDetail.getProvidentFundEnterprises(); //企业支出的公积金
            BigDecimal e2 = archiveDetail.getSocialSecurityEnterprise() == null ? new BigDecimal(0) : archiveDetail.getSocialSecurityEnterprise();//企业支出的社保金额
            BigDecimal p1 = archiveDetail.getProvidentFundIndividual() == null ? new BigDecimal(0) : archiveDetail.getProvidentFundIndividual();//个人支出的公积金
            BigDecimal p2 = archiveDetail.getSocialSecurityIndividual() == null ? new BigDecimal(0) : archiveDetail.getSocialSecurityIndividual();//个人支出的社保金额
            enterMoney = enterMoney.add(e1).add(e2);
            personMoney = personMoney.add(p1).add(p2);
        }
        Archive archive = findArchive(companyId, yearMonth);
        //存在则覆盖，否则保存
        if (archive == null){
            archive = new Archive(new Date());
            archive.setCompanyId(companyId);
            archive.setYearsMonth(yearMonth);
            archive.setId(idWorker.nextId()+"");
        }
        archive.setEnterprisePayment(personMoney);
        archive.setEnterprisePayment(enterMoney);
        archive.setTotal(personMoney.add(enterMoney));
        archiveDao.save(archive);
        for (ArchiveDetail archiveDetail : archiveDetails) {
            archiveDetail.setId(idWorker.nextId()+"");
            archiveDetail.setArchiveId(archive.getId());
            archiveDetailDao.save(archiveDetail);
        }
    }


    public List<Archive> findArchiveByYear(String companyId, String year) {
        return archiveDao.findByCompanyIdAndYearsMonthLike(companyId, year);
    }

    public ArchiveDetail findUserArchiveDetail(String userId, String yearMonth) {
        return archiveDetailDao.findByUserIdAndYearsMonth(userId,yearMonth);
    }
}
